//
//  JFBSetting.h
//  com.jufangbian.m
//
//  Created by feynmanyuan on 15/4/17.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "NSString+Utilities.h"

static NSString *const XCRGXName			= @"^(?!`\\s*$).+";
static NSString *const XCRGXEmailAddress	= @"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?"; // RFC 2822
static NSString *const XCRGXUsername		= @"^[\\w.@+-]+$";
static NSString *const XCRGXPassword		= @"^(?=[0-9a-zA-Z]{6}).{6,20}$";
static NSString *const XCRGXHTTPURL         = @"http://([w-]+.)+[w-]+(/[w- ./?%&=]*)?";

@implementation NSString (Utilities)

+ (BOOL)isNilOrEmpty:(NSString *)string
{
	return (!string || [string length] <= 0);
}

+ (BOOL)isNilOrEmptyOrWhitespace:(NSString *)string
{
	return (!string || [string isEqual:[NSNull null]] || [[string trimmedString] length] <= 0);
}

+ (NSString *)nonNullString:(NSString *)string
{
	return (string ? string : [NSString string]);
}

+ (NSString *)nonEmptyStringOrNil:(NSString *)string
{
	if ([self isNilOrEmpty:string])
    {
		return nil;
    }
	return string;
}

+ (NSString *)nonEmptyTrimmedStringOrNil:(NSString *)string
{
	if ([self isNilOrEmptyOrWhitespace:string])
    {
        return nil;
    }
	return [string trimmedString];
}

+ (NSString *)newUUIDString
{
	CFUUIDRef theUUID = CFUUIDCreate(NULL);
    //( NSString *)CFUUIDCreateString(NULL, theUUID);
	NSString *string = ( NSString *)CFBridgingRelease(CFUUIDCreateString(NULL, theUUID));
	CFRelease(theUUID);
	return string;
}

- (CGSize)sizeWithFont:(UIFont *)font byWidth:(CGFloat)width
{
    return [self sizeWithFont:font
            constrainedToSize:CGSizeMake(width, 999999.0f)
                lineBreakMode: NSLineBreakByWordWrapping];
}

- (CGSize)sizeWithFont:(UIFont *)font byHeight:(CGFloat)height
{
    return [self sizeWithFont:font
            constrainedToSize:CGSizeMake(999999.0f, height)
                lineBreakMode: NSLineBreakByWordWrapping];
}
/*
+ (NSString *)timestampString:(int)unixTimestamp
{
    NSTimeInterval nowInterval = [[NSDate date] timeIntervalSince1970];
    int now = [[NSNumber numberWithInt:nowInterval] intValue] + (60 * 60 * 8);
    int timePassed =  now - unixTimestamp;
    if (timePassed < 60) {
        // display in seconds.
        return @"刚刚";
    } 
    else if (timePassed > 60 && timePassed < 3600) {
        // display in minutes.
        int minutes = timePassed / 60;
        return [NSString stringWithFormat:@"%d分钟前", minutes];
    } 
    else if (timePassed >= 3600 && timePassed < (3600 * 24)) {
        // display in hours.
        int hours = timePassed / 3600;
        return [NSString stringWithFormat:@"%d小时前", hours];
    } 
    // display in MM-dd hh:mm
    else {
        NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
        [formatter setDateFormat:@"MM-dd hh:mm"];
        return [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:unixTimestamp]];
    }
}
*/

/*
+ (NSString *)fullNameStringWithFirstName:(NSString *)firstName lastName:(NSString *)lastName
{
	// ABPersonGetCompositeNameFormat() result is not reliable unless an ABAddressBookRef is first created
	static ABAddressBookRef addressBook;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		
		addressBook = ABAddressBookCreate();
		
	});
	
	NSString *firstNameLastNameFormat;
	switch (ABPersonGetCompositeNameFormat()) {
            
		case kABPersonCompositeNameFormatFirstNameFirst:
        firstNameLastNameFormat = @"%1$@ %2$@";
        break;
            
		case kABPersonCompositeNameFormatLastNameFirst:
		default:
        firstNameLastNameFormat = @"%2$@ %1$@";
        break;
	}
	
	return [[NSString stringWithFormat:
			 firstNameLastNameFormat,
			 firstName,
			 lastName] trimmedString];
}
*/

- (BOOL)contains:(NSString *)substring
{
	return ([self rangeOfString:substring].location != NSNotFound);
}

- (NSString *)URLEncodedString
{
//    NSString *encoded = (NSString *)
//	CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
//											( CFStringRef)self,
//											NULL,
//                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
//                                            kCFStringEncodingUTF8);
    NSString *encoded = (NSString *)
	CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
											( CFStringRef)self,
											NULL,
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8));
	return encoded ;
}

- (NSString *)URLDecodedString
{
	return [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)trimmedString
{
	return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSNumber *)numberWithString
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
	 NSNumber *number = [formatter numberFromString:self];
    return number;
}

- (BOOL)isValidName
{
	return ([self rangeOfString:XCRGXName options:NSRegularExpressionSearch].location != NSNotFound);
}

- (BOOL)isValidEmail
{
	return ([self rangeOfString:XCRGXEmailAddress options:NSRegularExpressionSearch].location != NSNotFound);
}

- (BOOL)isValidUsername
{
	return ([self rangeOfString:XCRGXUsername options:NSRegularExpressionSearch].location != NSNotFound);
}

- (BOOL)isValidPassword
{
	return ([self rangeOfString:XCRGXPassword options:NSRegularExpressionSearch].location != NSNotFound);
}

- (BOOL)isValidMobileNumber
{
    /**
     
     *
     手机号码
     
     *
     移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     
     *
     联通：130,131,132,152,155,156,185,186
     
     *
     电信：133,1349,153,180,189
     
     */
    
    NSString *MOBILE = @"^1(3[0-9]|5[0-35-9]|7[0-9]|8[025-9])\\d{8}$";
    
    /**
     
     *
     中国移动：China Mobile
     
     *
     134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     
     */
    NSString *CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    
    /**
     
     *
     中国联通：China Unicom
     
     *
     130,131,132,152,155,156,185,186
     
     */
    NSString *CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    
    /**
     
     *
     中国电信：China Telecom
     
     *
     133,1349,153,180,189
     
     */
    NSString *CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    
    /**
     
     *
     大陆地区固话及小灵通
     
     *
     区号：010,020,021,022,023,024,025,027,028,029
     
     *
     号码：七位或八位
     
     */
    
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSString *VIS = @"^170\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    NSPredicate *regextestvis = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", VIS];
    
    if (([regextestmobile evaluateWithObject:self] == YES) ||
       ([regextestcm evaluateWithObject:self] == YES) ||
        ([regextestct evaluateWithObject:self] == YES) ||
        ([regextestcu evaluateWithObject:self] == YES) ||
        ([regextestvis evaluateWithObject:self] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (BOOL)isValidateCarNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    return [carTest evaluateWithObject:self];
}

+ (BOOL)isValidateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    return [carTest evaluateWithObject:carNo];
}

-(NSMutableArray *)substringByRegular:(NSString *)regular
{
    NSRange r = [self rangeOfString:regular options:NSRegularExpressionSearch];
    
    NSMutableArray *arr = [NSMutableArray array];
    
    if (r.length != NSNotFound &&r.length != 0) {
        
        while (r.length != NSNotFound &&r.length != 0) {
            
            NSString* substr = [self substringWithRange:r];
            [arr addObject:substr];
            NSRange startr = NSMakeRange(r.location+r.length, [self length]-r.location-r.length);
            r = [self rangeOfString:regular options:NSRegularExpressionSearch range:startr];
        }
    }
    return arr;
}

+(NSDecimalNumber *)formatDecimal:(id)value{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:0];
    [numberFormatter setMaximumFractionDigits:2];
    NSString *string = [numberFormatter stringFromNumber:value];
    return [NSDecimalNumber decimalNumberWithString:string];
}

+(NSString*)decimalToString:(NSDecimalNumber*)value {
    return [NSString stringWithFormat:@"%.01f", [value doubleValue]];
}

@end
